package edu.hawaii.ics.pjdb.result_transport;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.hawaii.ics.pjdb.types.Tuple;

/**
 * logs any tuples it receives to SLF4j
 * 
 * @author chris
 * 
 */
public class LoggingTupleListener extends TupleListener {
    private static final Logger logger = LoggerFactory
            .getLogger(LoggingTupleListener.class);

    public static class Builder extends TupleListener.Builder {
        private final TupleListener.Builder innerBuilder;

        public Builder(TupleListener.Builder innerBuilder) {
            this.innerBuilder = innerBuilder;
        }

        public Builder() {
            this.innerBuilder = null;
        }

        @Override
        public TupleListener create() {
            if (innerBuilder == null) {
                return new LoggingTupleListener();
            } else {
                return new LoggingTupleListener(innerBuilder.create());
            }
        }

        @Override
        public Builder withLogging() {
            return this;
        }
    }

    private final TupleListener inner;

    public LoggingTupleListener() {
        this.inner = null;
    }

    public LoggingTupleListener(TupleListener inner) {
        this.inner = inner;
    }

    @Override
    public void receiveTuples(List<Tuple> tuples) {
        logger.info("Received tuple group containing {} tuples:", tuples.size());

        for (int i = 1; i <= tuples.size(); i++) {
            logger.info("\tTuple #{}: {}", i, tuples.get(i - 1));
        }

        inner.receiveTuples(tuples);
    }

    @Override
    public void finished() {
        logger.info("LoggingTupleListener#finished() called.");
        inner.finished();
    }

}
